package com.lemzdo.community.provider;

import com.alibaba.fastjson.JSON;
import com.lemzdo.community.dto.AccessTokenDTO;
import com.lemzdo.community.dto.GiteeUserDTO;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

//gitee提供者 提供对第三方的支持
@Component//将当前类放入spring容器
public class GiteeProvider {

    /**
     * 根据gitee返回来的code获取access-token 使用的是okHttp的post请求方式
     *
     * @param accessTokenDTO 用来传输access_token的数据传输模型 里面有uri,id,secret,code等参数
     * @return access-token字符串
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO) {

        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        //JSON.toJSONString(accessTokenDTO) 将其他对象转换为json字符串形式
        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokenDTO), mediaType);
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" + accessTokenDTO.getCode()
                        + "&client_id=" + accessTokenDTO.getClient_id()
                        + "&redirect_uri=" + accessTokenDTO.getRedirect_uri()
                        + "&client_secret=" + accessTokenDTO.getClient_secret())
                //"https://gitee.com/oauth/token?grant_type=authorization_code&code="+code+"&client_id="+CLIENT_ID+"&redirect_uri="+REDIRECTURI+"&client_secret="+CLIENT_SECRET;
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            //System.out.println(string);
            //{"access_token":"55605cfd91f6008bcf1008c4103d6e5b",
            // "token_type":"bearer",
            // "expires_in":86400,
            // "refresh_token":"ea4a92af19417ee05eeb2f9aeeb82e96f4b4b40954594d20aa420c7b5ed1f321",
            // "scope":"user_info",
            // "created_at":1589781902}

            //将得到的string进行删减 取得需要的access_token
            String[] splitStr = string.split(",");
            String tokenStr = splitStr[0];
            //{"access_token":"55605cfd91f6008bcf1008c4103d6e5b"
            tokenStr = tokenStr.split(":")[1];
            //"55605cfd91f6008bcf1008c4103d6e5b"
            tokenStr = tokenStr.replace("\"","").replace("\"","");

            //System.out.println(tokenStr);
            //55605cfd91f6008bcf1008c4103d6e5b
            return tokenStr;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据gitee返回来的access-token 来获取需要用到的一些用户信息 使用的是okHttp的get请求方式
     * @param accessToken gitee返回来的access-token
     * @return 一个用户数据模型
     */
    public GiteeUserDTO getUser(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();

            //System.out.println(string);
            //{"id":7574871,"login":"lemzdo","name":"lemzdo",
            // "avatar_url":"https://gitee.com/assets/no_portrait.png",
            // "url":"https://gitee.com/api/v5/users/lemzdo",
            // "html_url":"https://gitee.com/lemzdo",
            // "followers_url":"https://gitee.com/api/v5/users/lemzdo/followers",
            // "following_url":"https://gitee.com/api/v5/users/lemzdo/following_url{/other_user}",
            // "gists_url":"https://gitee.com/api/v5/users/lemzdo/gists{/gist_id}",
            // "starred_url":"https://gitee.com/api/v5/users/lemzdo/starred{/owner}{/repo}",
            // "subscriptions_url":"https://gitee.com/api/v5/users/lemzdo/subscriptions",
            // "organizations_url":"https://gitee.com/api/v5/users/lemzdo/orgs",
            // "repos_url":"https://gitee.com/api/v5/users/lemzdo/repos",
            // "events_url":"https://gitee.com/api/v5/users/lemzdo/events{/privacy}",
            // "received_events_url":"https://gitee.com/api/v5/users/lemzdo/received_events",
            // "type":"User","site_admin":false,"blog":null,"weibo":null,"bio":"",
            // "public_repos":1,"public_gists":0,"followers":0,"following":0,"stared":0,
            // "watched":1,"created_at":"2020-05-17T17:23:33+08:00",
            // "updated_at":"2020-05-18T11:14:01+08:00","email":null}

            //将一个json格式的对象 转换成java类对象(封装的对象可以取我们需要的部分信息)
            GiteeUserDTO giteeUser = JSON.parseObject(string, GiteeUserDTO.class);
            return giteeUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
